<template>
  <!--Modal修改账号-->
  <a-modal title="修改账号" :visible="visible" :confirm-loading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
    <a-spin :spinning="loading">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }" :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }">
        <a-row :gutter="24">
          <a-col :md="24" :sm="24">
            <a-form-model-item label="当前账号" prop="oldAccount">
              <a-input v-model="form.oldAccount" disabled> </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="输入密码" prop="pscode">
              <a-input type="password" v-model="form.pscode" placeholder="请输入密码" autocomplete="new-password" :disabled="disabledPscode"> </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24">
            <a-form-model-item label="输入新账号" prop="account">
              <a-input v-model="form.account" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :md="24" :sm="24" class="verification-code">
            <a-form-model-item label="输入验证码" prop="verificationCode">
              <a-input v-model="form.verificationCode" placeholder="请输入" class="verificationCode" :disabled="sussPscode" />
              <div class="code-btn-wrapper">
                <button class="code-btn" type="button" :disabled="(second > 0 && second < 60) || sending" @click="sendCode">
                  <template v-if="second > 0 && second < 60">
                    {{ second }} </template
                  >{{ codeText }}
                </button>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { updateAccount, sendVerifyCode, checkPhone, validate, checkPwd } from '@/api/system/system'
import { createValidator, isPhone, isPostCode } from '@/utils/regExpression' // 正则校验
import Vue from 'vue'
export default {
  name: 'modifyAccount',
  props: {
    visible: {
      value: false,
      type: Boolean
    }
  },
  data() {
    return {
      rules: {
        account: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        pscode: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        verificationCode: [{ required: true, validator: createValidator(isPostCode, '请输入6位数字验证码', true), trigger: 'blur' }]
      },
      confirmLoading: false,
      form: {
        account: '',
        pscode: '',
        oldAccount: '',
        verificationCode: ''
      },
      timer: null,
      // 验证码秒数
      second: 60,
      sending: false,
      userInfo: JSON.parse(sessionStorage.getItem('ycloud-user_info')),
      loading: false,
      disabledPscode: false,
      sussPscode: true
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(val) {
        if (val) {
          this.$set(this.form, 'pscode', null)
        }
      }
    },
    'form.account': {
      handler(newValue, oldValue) {
        this.$set(this.form, 'verificationCode', null)
        clearTimeout(this.timer)
        this.sussPscode = true
        this.second = 60
      },
      deep: true
      // immediate: true
    }
  },
  computed: {
    codeText() {
      return this.second === 60 || this.second === 0 ? '发送验证码' : '秒后重发'
    }
  },
  created() {
    this.form.oldAccount = this.userInfo?.username
  },
  methods: {
    /**
     * @description: 发送验证码
     * @param {void}
     * @return {void}
     */
    sendCode() {
      const reg = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/
      if (!this.form.pscode) {
        this.$message.warning('请输入密码')
      } else if (this.form.account === '' || this.form.account === undefined) {
        this.$message.warning('请输入手机号码')
      } else if (reg.test(this.form.account)) {
        this.checkPwdFn()
      } else {
      }
    },
    /**
     * @description: 校验密码
     * @param {void}
     * @return {void}
     */
    checkPwdFn() {
      this.sending = true
      let param = { pscode: this.form.pscode }
      checkPwd(param)
        .then((res) => {
          this.sending = false
          if (res.data.code == 200) {
            this.disabledPscode = true
            this.checkPhoneFn()
          } else {
            this.sending = false
            this.disabledPscode = false
            this.$message.warning(res.data)
          }
        })
        .catch((err) => {
          this.sending = false
          this.disabledPscode = false
          this.$message.warning(res.data)
        })
    },
    /**
     * @description: 校验手机号
     * @param {void}
     * @return {void}
     */
    checkPhoneFn() {
      let param = { phone: this.form.account }
      this.sending = true
      this.loading = true
      checkPhone(param)
        .then((res) => {
          this.loading = false
          if (res.data.code == '0') {
            this.succSendCode()
          } else {
            this.sending = false
          }
        })
        .catch((err) => {
          this.sending = false
          this.loading = false
        })
    },
     /**
     * @description: 校验手机号成功发送验证码
     * @param {void}
     * @return {void}
     */
    succSendCode() {
      this.sending = true
      this.loading = true
      sendVerifyCode({ to: this.form.account, templateCode: 1 })
        .then((res) => {
          if (res.code === 200) {
            this.loading = false
            this.$message.success('验证码发送成功')
            this.loop()
            this.sussPscode = false
          } else {
            this.loading = false
            this.$message.warning(res.data)
          }
        })
        .finally(() => {
          this.sending = false
          this.loading = false
        })
    },
    /**
     * @description: 验证码计时
     * @param {void}
     * @return {void}
     */
    loop() {
      this.timer = setTimeout(() => {
        clearTimeout(this.timer)
        this.timer = null
        if (this.second > 0) {
          this.second--
          this.loop()
        } else {
          this.second = 60
        }
      }, 1000)
    },
    /**
     *@desc 修改密码
     *@param {}
     */
    handleOk(e) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let params = { to: this.form.account, code: this.form.verificationCode }
          validate(params)
            .then((res) => {
              if (res.code == '200') {
                this.sureCode()
              } else {
                this.$message.warning(res.message)
              }
            })
            .catch((err) => {})
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     *@desc 确定发送验证码
     *@param {}
     */
    sureCode() {
      this.confirmLoading = true
      updateAccount(this.form)
        .then((res) => {
          if (res.data.code == '0') {
            this.$message.success('修改成功,请重新登录')
            let timer = setTimeout(() => {
              clearTimeout(timer)
              timer = null
              this.confirmLoading = false
              this.handleCancel()
              localStorage.removeItem('ycloud-user_info')
              Vue.getAcloudProvider().logout()
            }, 1000)
          } else {
            this.$message.warning(res.message)
            this.confirmLoading = false
          }
        })
        .catch((err) => {
          this.confirmLoading = false
        })
    },
    /**
     *@desc  重置取消
     *@param {}
     */
    handleCancel(e) {
      this.$refs.ruleForm.resetFields()
      this.$emit('handleCancel', false)
      this.second = 60
      this.disabledPscode = false
      this.confirmLoading = false
      this.sussPscode = true
      clearTimeout(this.timer)
    }
  }
}
</script>
<style scoped lang="less">
@deep: ~'>>>';
.disabled-pwd {
  text-security: disc;
  -webkit-text-security: disc;
  font-family: 'password';
}
.modalForm .ant-form-item .ant-form-item-control-wrapper {
  width: 90%;
  padding-left: 10%;
}
.verification-code {
  @{deep} .ant-form-item-children {
    display: flex;
    align-content: space-between;
    .verificationCode {
      width: calc(100% - 110px);
      margin-top: 5px;
    }
    .code-btn {
      width: 98px;
      margin-left: 10px;
      line-height: 26px;
      outline: none;
      border: 1px solid #3ca9e7;
      border-radius: 5px;
      text-align: center;
      color: #3ca9e7;
      background-color: transparent;
      cursor: pointer;
    }
  }
}
</style>
